package com.ibeeking.found.cop.cp.rest.service.impl;

import com.ibeeking.found.common.constants.WxCpServiceTypeConstant;
import com.ibeeking.found.common.entity.open.*;
import com.ibeeking.found.common.enums.OpenApiConfigEnum;
import com.ibeeking.found.common.enums.WxCpAppTypeEnum;
import com.ibeeking.found.cop.cp.rest.config.prop.RedisProperties;
import com.ibeeking.found.cop.cp.rest.service.IWxOpenService;
import com.ibeeking.found.cop.service.common.constants.RedisKeyConstant;
import com.ibeeking.gmc.global.api.feign.GlobalOpenFeignClient;
import com.ibeeking.nematos.core.utils.SpringBeanUtil;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.log.utils.LogUtils;
import com.ibeeking.nematos.redis.utils.RedisUtils;
import com.ibeeking.nematos.utils.result.ResponseResult;
import me.chanjar.weixin.common.bean.WxAccessToken;
import me.chanjar.weixin.common.redis.JedisWxRedisOps;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.config.WxCpTpConfigStorage;
import me.chanjar.weixin.cp.config.impl.WxCpTpJedisConfigImpl;
import me.chanjar.weixin.cp.config.impl.WxCpTpRedisConfigImpl;
import me.chanjar.weixin.cp.config.impl.WxCpTpRedissonConfigImpl;
import me.chanjar.weixin.cp.tp.service.WxCpTpService;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import me.chanjar.weixin.cp.config.impl.WxCpJedisConfigImpl;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 禁止在此类加其他业务方法
 *
 * @ClassName WxMpService
 * @Description
 * @Author ibeeking
 * @Date 2020-12-30 10:29
 **/
@Service
@EnableConfigurationProperties({RedisProperties.class})
public class WxOpenServiceImpl implements IWxOpenService {
    private Logger logger = LoggerFactory.getLogger(getClass());
    //30分钟
    private static final Long TIME = 7000L;

    @Resource
    private GlobalOpenFeignClient globalOpenFeignClient;

    @Autowired
    private RedisProperties redisProperties;

    @Resource
    private RedisUtils redisUtils;

    /**
     * 获取企业微信自建应用服务
     * @param
     * @return
     */
    @Override
    public WxCpService getWxCpService(Long tenantId) {
        try {
            OpenConfigDTO wxOpenConfigDTO = queryWxOpenConfigByType(OpenApiConfigEnum.OPEN_CONFIG_TYPE_WECHAT_CP.getCode(), WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_SB.getCode());
            if(wxOpenConfigDTO==null)  throw new BusinessException("企业微信自建应用OpenConfigDTO没有配置，请先配置!");

            OpenAuthDTO  wxOpenAuthDTO = queryWxOpenAuthByTenantId(tenantId, OpenApiConfigEnum.OPEN_CONFIG_TYPE_WECHAT_CP.getCode(), WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_SB.getCode(), WxCpServiceTypeConstant.CP_TYPE_SB);
            if(wxOpenAuthDTO == null) throw new BusinessException("企业微信自建应用OpenAuthDTO没有配置，请先配置!");
            WxCpService wxcCpService = SpringBeanUtil.getBean(WxCpService.class);
            if(wxcCpService == null) throw new BusinessException("get WxOpenService service error!");
            WxCpConfigStorage wxCpConfigStorage = getWxCpRedissonConfigStorage(tenantId, wxOpenConfigDTO, wxOpenAuthDTO);

            wxcCpService.setWxCpConfigStorage(wxCpConfigStorage);
            wxcCpService.getAccessToken(true);
            return wxcCpService;
        }catch(Exception ex){
            LogUtils.error(ex.toString());
            return null;
        }
    }

    /**
     * 获取企业微信三方应用服务
     * @param
     * @return
     */
    @Override
    public WxCpTpService getWxCpTpService(Long tenantId) {
        try {
            OpenConfigDTO wxOpenConfigDTO = queryWxOpenConfigByType(OpenApiConfigEnum.OPEN_CONFIG_TYPE_WECHAT_CP.getCode(), WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_TP.getCode());
            if(wxOpenConfigDTO==null)  throw new BusinessException("企业微信自建应用OpenConfigDTO没有配置，请先配置!");

            OpenAuthDTO  wxOpenAuthDTO = queryWxOpenAuthByTenantId(tenantId, OpenApiConfigEnum.OPEN_CONFIG_TYPE_WECHAT_CP.getCode(), WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_TP.getCode(), WxCpServiceTypeConstant.CP_TYPE_TP);
            if(wxOpenAuthDTO == null) throw new BusinessException("企业微信自建应用OpenAuthDTO没有配置，请先配置!");
            WxCpTpService wxCpTpService = SpringBeanUtil.getBean(WxCpTpService.class);
            if(wxCpTpService == null) throw new BusinessException("get WxOpenService service error!");
            WxCpTpConfigStorage wxCpTpConfigStorage = getWxCpTpRedissonConfigStorage(tenantId, wxOpenConfigDTO, wxOpenAuthDTO);

            wxCpTpService.setWxCpTpConfigStorage(wxCpTpConfigStorage);
            wxCpTpService.getSuiteAccessToken(true);
            return wxCpTpService;
        }catch(Exception ex){
            LogUtils.error(ex.toString());
            return null;
        }
    }

    /**
     * 获取企业微信三方应用服务
     * @param
     * @return
     */
    @Override
    public WxCpTpService getWxCpDkService(Long tenantId) {
        try {
            OpenConfigDTO wxOpenConfigDTO = queryWxOpenConfigByType(OpenApiConfigEnum.OPEN_CONFIG_TYPE_WECHAT_CP.getCode(), WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_DK.getCode());
            if(wxOpenConfigDTO==null)  throw new BusinessException("企业微信自建应用OpenConfigDTO没有配置，请先配置!");

            OpenAuthDTO  wxOpenAuthDTO = queryWxOpenAuthByTenantId(tenantId, OpenApiConfigEnum.OPEN_CONFIG_TYPE_WECHAT_CP.getCode(), WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_DK.getCode(), WxCpServiceTypeConstant.CP_TYPE_DK);
            if(wxOpenAuthDTO == null) throw new BusinessException("企业微信自建应用OpenAuthDTO没有配置，请先配置!");
            WxCpTpService wxCpTpService = SpringBeanUtil.getBean(WxCpTpService.class);
            if(wxCpTpService == null) throw new BusinessException("get WxOpenService service error!");
            WxCpTpConfigStorage wxCpConfigStorage = getWxCpDkRedissonConfigStorage(tenantId, wxOpenConfigDTO, wxOpenAuthDTO);

            wxCpTpService.setWxCpTpConfigStorage(wxCpConfigStorage);
            wxCpTpService.getSuiteAccessToken(true);
            return wxCpTpService;
        }catch(Exception ex){
            LogUtils.error(ex.toString());
            return null;
        }
    }

    private OpenConfigDTO queryWxOpenConfigByType(Integer configType, Integer configSubType) {
        OpenConfigQuery query = new OpenConfigQuery();
        query.setType(configType);
        query.setSubType(configSubType);
        ResponseResult<OpenConfigDTO> responseResult = globalOpenFeignClient.queryOpenConfigOne(query);
        return responseResult.getData();
    }

    private OpenAuthDTO queryWxOpenAuthByTenantId(Long tenantId, Integer configType, Integer configSubType, Integer appType) {
        OpenAuthQuery query = new OpenAuthQuery();
        query.setTenantId(tenantId);
        query.setConfigType(configType);
        query.setConfigSubType(configSubType);
        query.setAppType(appType);
        ResponseResult<OpenAuthDTO> responseResult = globalOpenFeignClient.queryOpenAuthOne(query);
        return responseResult.getData();
    }

    private WxCpConfigStorage getWxCpRedissonConfigStorage(Long tenantId, OpenConfigDTO wxOpenConfigDTO, OpenAuthDTO wxOpenAuthDTO) {
        OpenAuthOfExtend openAuthOfExtend = wxOpenAuthDTO.getOpenAuthOfExtend();
        if(openAuthOfExtend == null) throw new BusinessException("企业微信自建应用没有配置，请先配置!");
        OpenAuthOfWxCpSb  openAuthOfWxCpSb = openAuthOfExtend.getOpenAuthOfWxCpSb();
        WxCpJedisConfigImpl wxCpJedisConfigImpl = new WxCpJedisConfigImpl(redisProperties.getJedisPool(), "wx:cp:sb:".concat(tenantId.toString()));

        wxCpJedisConfigImpl.setCorpId(wxOpenAuthDTO.getOpenAppId());
        wxCpJedisConfigImpl.setCorpSecret(wxOpenAuthDTO.getAppSecret());
        wxCpJedisConfigImpl.setToken(wxOpenAuthDTO.getAppToken());
        wxCpJedisConfigImpl.setAesKey(wxOpenAuthDTO.getAppAesKey());
        OpenConfigOfExtend openConfigOfExtend = wxOpenConfigDTO!=null?wxOpenConfigDTO.getOpenConfigOfExtend():null;
        OpenConfigOfWxCp openConfigOfWxCp = openConfigOfExtend!=null?openConfigOfExtend.getOpenConfigOfWxCp():null;
        OpenConfigOfWxCpTalkData openConfigOfWxCpTalkData = openConfigOfWxCp!=null?openConfigOfWxCp.getWxCpTalkData():null;
        if(openConfigOfWxCpTalkData!=null) {
            wxCpJedisConfigImpl.setMsgAuditSecret(openConfigOfWxCpTalkData.getTalkDataSecret());
            wxCpJedisConfigImpl.setMsgAuditPriKey(openConfigOfWxCpTalkData.getTalkDataPriKey());
            wxCpJedisConfigImpl.setMsgAuditLibPath(openConfigOfWxCpTalkData.getTalkDataLibPath());
        }
        if(StringUtils.isNotEmpty(wxOpenAuthDTO.getAppId())) {
            Integer agentId  = Integer.parseInt(wxOpenAuthDTO.getAppId());
            wxCpJedisConfigImpl.setAgentId(agentId);
        }
        if(StringUtils.isNotEmpty(openAuthOfWxCpSb.getAccessToken())){
            WxAccessToken wxAccessToken = new WxAccessToken();
            wxAccessToken.setAccessToken(openAuthOfWxCpSb.getAccessToken());
            wxAccessToken.setExpiresIn(openAuthOfWxCpSb.getAccessTokenExpiresTime());
            wxCpJedisConfigImpl.updateAccessToken(wxAccessToken);
        }
        return wxCpJedisConfigImpl;
    }

    private WxCpTpConfigStorage getWxCpTpRedissonConfigStorage(Long tenantId, OpenConfigDTO openConfigDTO, OpenAuthDTO wxOpenAuthDTO) {
        Integer configType = OpenApiConfigEnum.OPEN_CONFIG_TYPE_WECHAT_CP.getCode();
        Integer configSubType = WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_TP.getCode();
        String openConfigKey = "wx:cp:tp:t".concat(configType.toString()).concat(":s").concat(configSubType.toString());
        OpenAuthOfExtend openAuthOfExtend = wxOpenAuthDTO.getOpenAuthOfExtend();
        if(openAuthOfExtend == null) throw new BusinessException("企业微信三方应用没有配置，请先配置!");
        OpenAuthOfWxCpTp  openAuthOfWxCpTp = openAuthOfExtend.getOpenAuthOfWxCpTp();

        JedisWxRedisOps wxRedisOps = new JedisWxRedisOps(redisProperties.getJedisPool());
        String suiteId = openConfigDTO.getComponentAppId();
        WxCpTpRedissonConfigImpl.WxCpTpRedissonConfigImplBuilder configStorageBuider = WxCpTpRedissonConfigImpl.builder().wxRedisOps(wxRedisOps);

        if(StringUtils.isNotEmpty(openConfigKey))configStorageBuider.keyPrefix(openConfigKey);
        if(StringUtils.isNotEmpty(openConfigDTO.getOpenAppId()))configStorageBuider.corpId(openConfigDTO.getOpenAppId());
        if(StringUtils.isNotEmpty(openConfigDTO.getOpenAppSecret()))configStorageBuider.corpSecret(openConfigDTO.getOpenAppSecret());
        if(StringUtils.isNotEmpty(openConfigDTO.getComponentAppId()))configStorageBuider.suiteId(suiteId);
        if(StringUtils.isNotEmpty(openConfigDTO.getComponentSecret()))configStorageBuider.suiteSecret(openConfigDTO.getComponentSecret());
        if(StringUtils.isNotEmpty(openConfigDTO.getComponentMsgToken()))configStorageBuider.token(openConfigDTO.getComponentMsgToken());
        if(StringUtils.isNotEmpty(openConfigDTO.getComponentMsgAesKey()))configStorageBuider.aesKey(openConfigDTO.getComponentMsgAesKey());
        if(StringUtils.isNotEmpty(openConfigDTO.getHttpProxyHost()))configStorageBuider.httpProxyHost(openConfigDTO.getHttpProxyHost());
        if(null!=openConfigDTO.getHttpProxyPort())configStorageBuider.httpProxyPort(openConfigDTO.getHttpProxyPort());
        if(StringUtils.isNotEmpty(openConfigDTO.getHttpProxyUsername()))configStorageBuider.httpProxyUsername(openConfigDTO.getHttpProxyUsername());
        if(StringUtils.isNotEmpty(openConfigDTO.getHttpProxyPassword()))configStorageBuider.httpProxyPassword(openConfigDTO.getHttpProxyPassword());

        WxCpTpConfigStorage configStorage = configStorageBuider.build();

        Object suiteTicket = redisUtils.get(RedisKeyConstant.WX_CP_TP_SUITE_TICKET.concat(suiteId));
        Object suiteAccessTokenObj = redisUtils.get(RedisKeyConstant.WX_CP_TP_SUITE_ACCESS_TOKEN.concat(suiteId));

        if(ObjectUtils.isNotEmpty(suiteTicket)){
            configStorage.updateSuiteTicket(suiteTicket.toString(), 1200);
        }
        if(ObjectUtils.isNotEmpty(suiteAccessTokenObj)) {
            WxAccessToken suiteAccessTokenEntity = (WxAccessToken)suiteAccessTokenObj;
            if(StringUtils.isNotEmpty(suiteAccessTokenEntity.getAccessToken())) {
                configStorage.updateSuiteAccessToken(suiteAccessTokenEntity);
            }else{
                OpenConfigOfExtend openConfigOfExtend = openConfigDTO!=null?openConfigDTO.getOpenConfigOfExtend():null;
                OpenConfigOfWxCp openConfigOfWxCp = openConfigOfExtend != null ?openConfigOfExtend.getOpenConfigOfWxCp():null;
                suiteAccessTokenEntity.setAccessToken(openConfigOfWxCp.getComponentAccessToken());
                suiteAccessTokenEntity.setExpiresIn(7200);
                configStorage.updateSuiteAccessToken(suiteAccessTokenEntity);
            }
        }
        return configStorage;
    }

    private WxCpTpConfigStorage getWxCpDkRedissonConfigStorage(Long tenantId, OpenConfigDTO openConfigDTO, OpenAuthDTO wxOpenAuthDTO) {
        Integer configType = OpenApiConfigEnum.OPEN_CONFIG_TYPE_WECHAT_CP.getCode();
        Integer configSubType = WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_DK.getCode();
        String openConfigKey = "wx:cp:dk:t".concat(configType.toString()).concat(":s").concat(configSubType.toString());
        OpenAuthOfExtend openAuthOfExtend = wxOpenAuthDTO.getOpenAuthOfExtend();
        if(openAuthOfExtend == null) throw new BusinessException("企业微信三方应用没有配置，请先配置!");
        OpenAuthOfWxCpTp  openAuthOfWxCpTp = openAuthOfExtend.getOpenAuthOfWxCpTp();

        OpenConfigOfExtend openConfigOfExtend = openConfigDTO!=null?openConfigDTO.getOpenConfigOfExtend():null;
        OpenConfigOfWxCp openConfigOfWxCp = openConfigOfExtend != null ?openConfigOfExtend.getOpenConfigOfWxCp():null;
        JedisWxRedisOps wxRedisOps = new JedisWxRedisOps(redisProperties.getJedisPool());
        String suiteId = openConfigDTO.getComponentAppId();
        WxCpTpRedissonConfigImpl.WxCpTpRedissonConfigImplBuilder configStorageBuider = WxCpTpRedissonConfigImpl.builder().wxRedisOps(wxRedisOps);
        if(StringUtils.isNotEmpty(openConfigKey))configStorageBuider.keyPrefix(openConfigKey);
        if(StringUtils.isNotEmpty(openConfigDTO.getOpenAppId()))configStorageBuider.corpId(openConfigDTO.getOpenAppId());
        if(StringUtils.isNotEmpty(openConfigDTO.getOpenAppSecret()))configStorageBuider.corpSecret(openConfigDTO.getOpenAppSecret());
        if(StringUtils.isNotEmpty(openConfigDTO.getComponentAppId()))configStorageBuider.suiteId(suiteId);
        if(StringUtils.isNotEmpty(openConfigDTO.getComponentSecret()))configStorageBuider.suiteSecret(openConfigDTO.getComponentSecret());
        if(StringUtils.isNotEmpty(openConfigDTO.getComponentMsgToken()))configStorageBuider.token(openConfigDTO.getComponentMsgToken());
        if(StringUtils.isNotEmpty(openConfigDTO.getComponentMsgAesKey()))configStorageBuider.aesKey(openConfigDTO.getComponentMsgAesKey());
        if(StringUtils.isNotEmpty(openConfigDTO.getHttpProxyHost()))configStorageBuider.httpProxyHost(openConfigDTO.getHttpProxyHost());
        if(null!=openConfigDTO.getHttpProxyPort())configStorageBuider.httpProxyPort(openConfigDTO.getHttpProxyPort());
        if(StringUtils.isNotEmpty(openConfigDTO.getHttpProxyUsername()))configStorageBuider.httpProxyUsername(openConfigDTO.getHttpProxyUsername());
        if(StringUtils.isNotEmpty(openConfigDTO.getHttpProxyPassword()))configStorageBuider.httpProxyPassword(openConfigDTO.getHttpProxyPassword());

        OpenConfigOfWxCpProvider wxCpProvider = openConfigOfWxCp!=null?openConfigOfWxCp.getWxCpProvider():null;
        String providerSecret = wxCpProvider!=null?wxCpProvider.getProviderSecret():null;
        if(StringUtils.isNotEmpty(providerSecret))configStorageBuider.providerSecret(providerSecret);

        WxCpTpConfigStorage configStorage = configStorageBuider.build();

        String suiteTicket = redisUtils.getString(RedisKeyConstant.WX_CP_DK_SUITE_TICKET.concat(suiteId));
        Object suiteAccessTokenObj = redisUtils.get(RedisKeyConstant.WX_CP_DK_SUITE_ACCESS_TOKEN.concat(suiteId));

        if(StringUtils.isNotEmpty(suiteTicket)){
            configStorage.updateSuiteTicket(suiteTicket, 1200);
        }
        if(ObjectUtils.isNotEmpty(suiteAccessTokenObj)) {
            WxAccessToken suiteAccessTokenEntity = (WxAccessToken)suiteAccessTokenObj;
            if(StringUtils.isNotEmpty(suiteAccessTokenEntity.getAccessToken())) {
                configStorage.updateSuiteAccessToken(suiteAccessTokenEntity);
            }else{
                suiteAccessTokenEntity.setAccessToken(openConfigOfWxCp.getComponentAccessToken());
                suiteAccessTokenEntity.setExpiresIn(7200);
                configStorage.updateSuiteAccessToken(suiteAccessTokenEntity);
            }
        }
        return configStorage;
    }

}